/**
 * Copyright (c) 2016-2019 ykf All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.basic.modules.sys.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.basic.common.annotation.StringTrim;
import com.basic.common.annotation.SysLog;
import com.basic.common.exception.RRException;
import com.basic.common.utils.Constant;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.R;
import com.basic.common.validator.Assert;
import com.basic.common.validator.ValidatorUtils;
import com.basic.common.validator.group.AddGroup;
import com.basic.common.validator.group.UpdateGroup;
import com.basic.modules.sys.entity.SysRoleEntity;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.form.PasswordForm;
import com.basic.modules.sys.service.SysUserRoleService;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.YkfDictDetailEntity;
import com.basic.modules.ykf.entity.YkfDictEntity;
import com.basic.modules.ykf.service.SmsService;
import com.basic.modules.ykf.service.YkfDictDetailService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class  SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private SmsService smsService;

	@Autowired
	private YkfDictDetailService dictDetailService;

	/**
	 * 所有用户列表
	 */
	@StringTrim
	@PostMapping("/list")
	public R list(@RequestBody ParamsModel<SysUserEntity> params){
		//只有超级管理员，才能查看所有管理员列表
//		if(getUserId() != Constant.SUPER_ADMIN){
//			params.getCondition().setCreateUserId(getUserId());
//		}
		PageUtils page = sysUserService.queryPage(params);
		return R.ok(page);
	}

	/**
	 * 客服用户列表
	 */
	@StringTrim
	@PostMapping("/cusSerList")
	public R cusSerList(@RequestBody ParamsModel<SysUserEntity> params){
		//只有超级管理员，才能查看所有管理员列表
//		if(getUserId() != Constant.SUPER_ADMIN){
//			params.getCondition().setCreateUserId(getUserId());
//		}
		PageUtils page = sysUserService.queryCusSerPage(params);
		return R.ok(page);
	}

	/**
	 * 更新客服用户
	 */
	@PostMapping("/updateCusSer")
	public R updateCusSer(@RequestBody SysUserEntity sysUser){
		if (ObjectUtil.isNotEmpty(sysUser) && ObjectUtil.isNotEmpty(sysUser.getUserId())) {
			UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().eq(SysUserEntity::getUserId, sysUser.getUserId())
					.set(SysUserEntity::getSex, sysUser.getSex())
					.set(SysUserEntity::getCustomGroup, sysUser.getCustomGroup())
					.set(SysUserEntity::getCustomGroupName, sysUser.getCustomGroupName())
					.set(SysUserEntity::getGroupNo, sysUser.getGroupNo())
					.set(SysUserEntity::getCustomPostType, sysUser.getCustomPostType())
					.set(SysUserEntity::getCustomPostTypeName, sysUser.getCustomPostTypeName());
			sysUserService.update(updateWrapper);
		} else {
			throw new RRException("参数缺失");
		}
		return R.ok();
	}

	/**
	 * 清空编组
	 */
	@PostMapping("/clearGroup")
	public R clearGroup(@RequestBody SysUserEntity sysUser){
		if (ObjectUtil.isNotEmpty(sysUser) && ObjectUtil.isNotEmpty(sysUser.getUserId())) {
			UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().eq(SysUserEntity::getUserId, sysUser.getUserId())
					.set(SysUserEntity::getGroupNo, "");
			sysUserService.update(updateWrapper);
		} else {
			throw new RRException("参数缺失");
		}
		return R.ok();
	}

	/**
	 * 修改黑/白名单
	 */
	@StringTrim
	@PostMapping("/changeList")
	public R changeList(@RequestBody SysUserEntity sysUser){
		if (ObjectUtil.isNotEmpty(sysUser) && ObjectUtil.isNotEmpty(sysUser.getUserId())) {
			UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().eq(SysUserEntity::getUserId, sysUser.getUserId())
					.set(SysUserEntity::getListName, sysUser.getListName());
			sysUserService.update(updateWrapper);
		} else {
			throw new RRException("参数缺失");
		}
		return R.ok();
	}

	/**
	 * 获取登录的用户信息
	 */
	@PostMapping("/personalInfo")
	public R info(){
		return R.ok(sysUserService.getById(getUserId()));
	}


	/**
	 * 更新用户个人信息
	 */
	@PostMapping("/updatePersonalInfo")
	public R updatePersonalInfo(@RequestBody SysUserEntity user){
		UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda().eq(SysUserEntity::getUserId, user.getUserId())
				.set(SysUserEntity::getFlowerName, user.getFlowerName())
				.set(SysUserEntity::getName, user.getName())
				.set(SysUserEntity::getMobile, user.getMobile())
				.set(SysUserEntity::getTel, user.getTel())
				.set(SysUserEntity::getOfficeLocation, user.getOfficeLocation());
		sysUserService.update(updateWrapper);
		return R.ok();
	}


	/**
	 * 用户信息
	 */
	@StringTrim
	@PostMapping("/info")
	public R info(@RequestBody SysUserEntity params){
		if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getUserId())) {
			throw new RRException("参数缺失");
		}
		SysUserEntity user = sysUserService.getById(params.getUserId());
//		//获取用户所属的角色列表
//		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
//		user.setRoleIdList(roleIdList);
		return R.ok(user);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	public R save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.saveUser(user);
		dictDetailService.updateDictMap("userName", StrUtil.toString(user.getUserId()), user.getName());
		dictDetailService.updateDictMap("flowerName", StrUtil.toString(user.getUserId()), user.getFlowerName());
		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	public R update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		dictDetailService.updateDictMap("userName", StrUtil.toString(user.getUserId()), user.getName());
		dictDetailService.updateDictMap("flowerName", StrUtil.toString(user.getUserId()), user.getFlowerName());

		return R.ok();
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}

		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}
		List<SysUserEntity> list = sysUserService.listByIds(Arrays.asList(userIds));
		sysUserService.deleteBatch(userIds);

		if (ObjectUtil.isNotEmpty(list)) {
			for (SysUserEntity item : list) {
				dictDetailService.updateDictMap("userName", StrUtil.toString(item.getUserId()), "");
				dictDetailService.updateDictMap("flowerName", StrUtil.toString(item.getUserId()), "");
			}
		}
		return R.ok();
	}

	/**
	 * 校验花名
	 */
	@SysLog("校验花名")
	@PostMapping("/validFlowerName")
	public R validFlowerName(@RequestBody SysUserEntity user){
		QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysUserEntity::getFlowerName, user.getFlowerName());
		if (ObjectUtil.isNotEmpty(user.getUserId())) {
			queryWrapper.lambda().ne(SysUserEntity::getUserId, user.getUserId());
		}
		if (sysUserService.count(queryWrapper) > 0) {
			throw new RRException("花名已存在，请检查");
		}
		return R.ok();
	}

	/**
	 * 校验工号
	 */
	@SysLog("校验工号")
	@PostMapping("/validNo")
	public R validNo(@RequestBody SysUserEntity user){
		QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysUserEntity::getNo, user.getNo());
		if (ObjectUtil.isNotEmpty(user.getUserId())) {
			queryWrapper.lambda().ne(SysUserEntity::getUserId, user.getUserId());
		}
		if (sysUserService.count(queryWrapper) > 0) {
			throw new RRException("工号已存在，请检查");
		}
		return R.ok();
	}

	/**
	 * 设置密码
	 */
	@SysLog("设置密码")
	@PostMapping("/setPassword")
	public R setPassword(@RequestBody PasswordForm form){
		Assert.isBlank(form.getPassword(), "密码不为能空");
		String salt = RandomStringUtils.randomAlphanumeric(20);
		//sha256加密
		String password = new Sha256Hash(form.getPassword(), salt).toHex();

//		//sha256加密
//		String newPassword = new Sha256Hash(form.getNewPassword(), user.getSalt()).toHex();

//		//更新密码
		sysUserService.updatePassword(form.getUserId(), password, salt);
//		if(!flag){
//			return R.error("原密码不正确");
//		}
		return R.ok();
	}

	/**
	 * 发送离职短信
	 */
	@SysLog("发送离职短信")
	@PostMapping("/sendResignationSms")
	public R sendResignationSms(@RequestBody SysUserEntity user) throws ClientException {
		if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(user.getUserId())) {
			SysUserEntity sysUser = sysUserService.getById(user.getUserId());
			if (ObjectUtil.isNotEmpty(sysUser) && StrUtil.isNotBlank(sysUser.getMobile())) {
				smsService.sendMsg(sysUser.getMobile(), "SMS_204125015", new HashMap<>());
				UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
				updateWrapper.lambda().eq(SysUserEntity::getUserId, user.getUserId())
						.set(SysUserEntity::getSendDepartMsg, 1);
				sysUserService.update(updateWrapper);
			} else {
				throw new RRException("手机号不存在，发送失败");
			}
		}
		return R.ok();
	}

}
